package com.im323.common.util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.io.FileUtils;

public class ConfigUtil {

	static {
		readConfig();
		readTmp();
	}

	private ConfigUtil() {

	}

	private static ConfigUtil config = null;
	private static boolean initFlag = false;

	private String lastIp = null;
	private String cron = null;
	private String logFile = null;

	public String getCron() {
		return cron;
	}

	public String getLogFile() {
		return logFile;
	}

	public static ConfigUtil getConfig() {
		return config;
	}

	private static void readConfig() {
		if (initFlag) {
			return;
		}
		initFlag = true;
		try {
			File file = new File("config.json");
			if (!file.exists()) {
				config = new ConfigUtil();
				return;
			}
			String content = FileUtils.readFileToString(file, "UTF-8");
			config = JsonUtil.toObj(content, ConfigUtil.class);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void readTmp() {
		try {
			File file = new File("tmp.ini");
			System.out.println(file.getAbsolutePath());
			if (!file.exists()) {
				return;
			}
			String string = FileUtils.readFileToString(file, "UTF-8");
			ConfigUtil configUtil = JsonUtil.toObj(string, ConfigUtil.class);
			if (configUtil != null) {
				config.lastIp = configUtil.lastIp;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void writeTmp() {
		File file = new File("tmp.ini");
		System.out.println(file.getAbsolutePath());
		try {
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			FileUtils.write(file, JsonUtil.toJson(config), "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
